<template>
    <div class="main settle-bill-list">
        <section>
            <div class="btn-block">
                <el-button type="success" plain size="small" @click="requestPush">推送账单</el-button>
                <el-button type="success" plain size="small" @click="exportSettleBill">导出结算单</el-button>
                <el-upload ref="importRef" accept=".xls,.xlsx" :show-file-list="false" style="display:inline-block;margin:0px 10px 0 10px" :action="''" :limit="1" :http-request="importExcel">
                    <el-button size="small" plain type="success">导入差额调整</el-button>
                </el-upload>
            </div>
            <el-form ref="searchForm" class="search-block" :model="listQuery" label-position="left" label-width="82px">
                <input type="text" style="display: none"/>
                <el-row :gutter="50">
                    <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="6">
                        <el-form-item label="结算单号：" prop="settle_no">
                            <el-input @keyup.enter.native="search" v-model="listQuery.settle_no" placeholder="结算单号" maxlength="50" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="6">
                      <el-form-item label="商家名称：" prop="account_id">
                        <el-select :filterable="true" v-model="listQuery.account_id" :clearable="true">
                            <el-option v-for="item in shopSelect" :key="item.id" :label="item.label" :value="item.value"></el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="6">
                      <el-form-item label="审核状态：" prop="status">
                        <el-select v-model="listQuery.status" :clearable="true">
                            <el-option v-for="item in auditStatus" :key="item.id" :label="item.label" :value="item.value"></el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="6">
                      <el-form-item label="账单周期：" prop="start_settle_date">
                        <el-date-picker value-format='yyyy-MM' @change="dateSet" v-model="listQuery.start_settle_date" type="month" placeholder="选择月"></el-date-picker>
                      </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item label="" class="btn-item">
                    <el-button type="primary" size="mini" icon="el-icon-search" plain @click="search">搜索</el-button>
                    <span class="btn-reset" @click="resetForm('searchForm')">清空搜索条件</span>
                </el-form-item>
            </el-form>
            <el-table type="selection" @selection-change="selectionChange" :data="list" v-loading="listLoading" header-row-class-name="table-header" element-loading-text="给我一点时间" border highlight-current-row>
                <el-table-column type="selection" width="50"></el-table-column>
                <el-table-column align="center" prop="settleNo" label="结算单号" min-width="100"></el-table-column>
                <el-table-column align="center" prop="merchantName" label="商家名称" min-width="150"></el-table-column>
                <el-table-column align="center" prop="settleCycle" label="账单周期" min-width="100">
                    <template slot-scope="scope">
                        <span>{{formatDate(scope.row.settleCycle, 'YYYY-MM-DD')}}</span>
                    </template>
                </el-table-column>
                <el-table-column align="center" prop="settleAmount" label="本期订单结算金额" min-width="100"></el-table-column>
                <el-table-column align="center" prop="refundAmount" label="本期退款金额" min-width="100"></el-table-column>
                <el-table-column :render-header="renderLastAlmount" align="center" prop="lastAmount" label="上期应结算金额" min-width="120"></el-table-column>
                <el-table-column :render-header="renderActualAmount" align="center" prop="actualAmount" label="本期结算合计" min-width="120"></el-table-column>
                <el-table-column align="center" prop="pushStatus" label="发送账单" min-width="100">
                    <template slot-scope="scope">
                        <span>{{scope.row.pushStatus==1?'已推送':'未推送'}}</span>
                    </template>
                </el-table-column>
                <el-table-column align="center" prop="auditStatus" label="状态" :formatter="auditStatusFormat" min-width="80"></el-table-column>
                <el-table-column align="center" prop="pushTime" label="发送账单时间" min-width="100">
                    <template slot-scope="scope">
                        <span>{{formatDate(scope.row.pushTime, 'YYYY-MM-DD HH:mm:ss')}}</span>
                    </template>
                </el-table-column>
                <el-table-column align="center" prop="settleTime" label="结算时间" min-width="100">
                    <template slot-scope="scope">
                        <span>{{formatDate(scope.row.settleTime, 'YYYY-MM-DD HH:mm:ss')}}</span>
                    </template>
                </el-table-column>
                <el-table-column align="center" prop="" label="操作" min-width="150" fixed="right">
                <template slot-scope="scope">
                    <el-button type="success" size="mini" @click="operate(scope.row.settleNo)" plain>查看</el-button>
                    <el-button v-if="scope.row.pushStatus==0" type="success" size="mini" @click="adjust(scope.row.settleNo)" plain>调整</el-button>
                    <el-button v-if="scope.row.pushStatus==0"  type="success" size="mini" @click="push(scope.row.accountId, scope.row.settleNo)" plain>推送账单</el-button>
                </template>
                </el-table-column>
            </el-table>
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page.sync="listQuery.page"
                    :page-sizes="[10, 20, 50, 100]"
                    :page-size="listQuery.page_size"
                    background
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="listTotal">
            </el-pagination>
        </section>
        <el-dialog title="调整" :visible.sync="showEditPop" :before-close="cancel">
            <el-form :model="editItem" :rules="editRule" size="medium" ref="editItem" label-width="120px">
                <el-form-item label="调整金额:" prop="adjust_amount">
                    <el-input-number v-model="editItem.adjust_amount" :max="1000000" label="描述文字"></el-input-number>
                </el-form-item>
                <el-form-item label="调整备注：" prop="adjust_remark">
                  <el-input type="textarea" :autosize="{ minRows: 5, maxRows: 5 }" v-model="editItem.adjust_remark"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="saveAdjust" >保存</el-button>
                <el-button @click="cancel">取消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
  import { getShopSelectList } from '@/api/merchantsys/goods'
  import { getSettleBillList, pushBill, adjustAmout, importAdjustAmount, exportBill } from '@/api/merchantsys/settle'
    export default {
        name: 'priceList',
        data() {
            return {
                showEditPop: false,
                shopSelect:[],
                settleNos: [],
                auditStatus: [
                    { label: '全部', value: null },
                    { label: '待确认', value: 1 },
                    { label: '已确认', value: 2 },
                    { label: '待结算', value: 3 },
                    { label: '已结算', value: 4 },
                    { label: '待复核', value: 5 },
                    { label: '复核通过', value: 6 },
                    { label: '复核驳回', value: 7 },
                    { label: '结算驳回', value: 8 }
                ],
                list: [],
                listQuery: {
                    start_settle_date: '',
                    end_settle_date: '',
                    account_id:'',
                    settle_no: '',
                    status: '',
                    page: 1,
                    page_size: 10
                },
                pList: [],
                listTotal: 0,
                listLoading: false,
                loading:false,
                pushItems: [],
                editItem:{
                    settle_no: '',
                    adjust_amount:'',
                    adjust_remark:''
                },
                editRule: {
                    adjust_amount:[
                        {required: true, message:'不能为空', trigger: 'blur'}
                    ],
                    adjust_remark:[
                        {required: true, message: '不能为空', trigger: 'blur'},
                        {max: 200, message: '不能超过200字符', trigger: 'blur'},
                    ]
                },
            }
        },
        created() {
            this.fetchShopSelectList()
            this.getList()
        },
        methods: {
            renderLastAlmount(){
                return (
                    <el-tooltip class="tooltip" content="上期应结算金额 = 复核金额+其他调整金额" effect="light" placement="top">
                        <div scoped-slot="content"><i class="el-icon-info"></i>上期应结算金额</div>
                    </el-tooltip>
                );
            },
            renderActualAmount(){
                return (
                    <el-tooltip class="tooltip" content="本期结算合计 = 本期订单结算金额 - 本期退款金额 + 上期应结算金额" effect="light" placement="top">
                        <div scoped-slot="content"><i class="el-icon-info"></i>本期结算合计</div>
                    </el-tooltip>
                );
            },
            //导入差额调整
            importExcel(params){
                let fd = new FormData()
                fd.append('file', params.file)
                this.$refs.importRef.clearFiles()
                importAdjustAmount(fd).then(res=>{
                    if(res.data){
                        this.$message.success('导入差额调整成功')
                        this.getList()
                    }
                }).catch(err=>{
                    this.$message.error(err.message)
                })
            },
            exportSettleBill(){
                exportBill({
                    settleNos: this.settleNos,
                    settleNo: this.listQuery.settle_no,
                    accountId: this.listQuery.account_id,
                    status: this.listQuery.status,
                    startSettleDate: this.listQuery.start_settle_date,
                    endSettleDate: this.listQuery.end_settle_date
                }).then(res=>{
                    this.downloadFile(res, '商家结算单.xlsx')
                })
            },
            saveAdjust(){
                this.$refs.editItem.validate(valid => {
                    if (!valid) {
                        return false
                    }
                    adjustAmout(this.editItem).then(res=>{
                        if(res.data){
                            this.$message.success('调整成功')
                            this.getList()
                            this.cancel()
                        }
                    })
                })
            },
            adjust(settleNo){
                this.showEditPop = true
                this.editItem.settle_no = settleNo
            },
            cancel(){
                this.showEditPop = false
                this.editItem = {}
            },
            //选择要导出的具体数据
            selectionChange(item) {
                this.pushItems = []
                this.settleNos = []
                item.map(k => {
                    this.pushItems.push({accountId: k.accountId, settleNo: k.settleNo})
                    this.settleNos.push(k.settleNo)
                })
            },
            push(accountId, settleNo){
                this.pushItems = []
                this.pushItems.push({accountId: accountId, settleNo: settleNo})
                pushBill({pushItems: this.pushItems}).then(res=>{
                    if(res.data){
                        this.$message.success('推送成功')
                        this.getList()
                    }
                })
            },
            requestPush(){
                if(this.pushItems.length<1){
                    this.$message.error('请选择推送对象')
                    return
                }
                pushBill({pushItems: this.pushItems}).then(res=>{
                    if(res.data){
                        this.$message.success('推送成功')
                        this.getList()
                    }
                })
            },
            dateSet(value){
                if(!value){
                    this.listQuery.start_settle_date = ''
                    this.listQuery.end_settle_date = ''
                    return
                }
                this.listQuery.start_settle_date = value+'-01'
                this.listQuery.end_settle_date = value+'-31'
            },
            auditStatusFormat(row) {
                return ['-', '待确认', '已确认', '待结算', '已结算', '待复核', '复核通过', '复核驳回', '结算驳回'][row.auditStatus]
            },
            operate(settleNo) {
                this.$router.push({ path: '/settle/detail/' + settleNo })
            },
            modify(processId) {
                this.$router.push({ path: '/goods/base/modify/' + processId })
            },
            //商家下拉列表
            fetchShopSelectList() {
                getShopSelectList().then(res => {
                    if (res.code == 200 && res.data) {
                        res.data.forEach(element => {
                            this.shopSelect.push({ label: element.merchantName, value: element.accountId })
                        })
                    }
                })
            },
            //请求商家列表数据
            getList() {
                this.listLoading = true;
                getSettleBillList(this.listQuery).then(res => {
                    this.list = res.data.data;
                    this.listTotal = res.data.total;
                    this.listLoading = false;
                }).catch(err => {
                    this.list = [];
                    this.listTotal = 0;
                    this.listLoading = false;
                })
            },
            // 清空搜索条件
            resetForm (formName) {
                this.$nextTick(() => {
                    this.$refs[formName].resetFields()
                })
            },
            // 搜索
            search() {
                this.listQuery.page = 1;
                this.getList();
            },
            //切换每页条数
            handleSizeChange (value) {
                this.listQuery.page_size = value;
                this.getList()
            },
            // 切换分页
            handleCurrentChange(page) {
                this.listQuery.page = page;
                this.getList();
            }
        }
    }
</script>

<style lang="scss">
  
</style>
